package com.java2104.controller;

import com.java2104.entity.LoginUser;
import com.java2104.service.LoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private LoginUserService loginUserService;

    /*@PostMapping("/login")
    @ResponseBody
    public String login(String loginName, String password, HttpSession session){
        LoginUser loginUser = loginUserService.login(loginName,password);
        if(loginUser!=null){
            session.setAttribute("loginUser",loginUser);
            return "success";
        }else {
            return "fail";
        }
    }*/

    @PostMapping("/login")
    public String login(String loginName, String password, HttpSession session, Model model){
        LoginUser loginUser = loginUserService.login(loginName,password);
        if(loginUser!=null){//登陆成功
            session.setAttribute("loginUser",loginUser);
            return "redirect:/index";
        }else {
            model.addAttribute("ret_msg","用户名或密码错误");
            return "/login";
        }
    }

    @GetMapping({"/edit_pass","/edit_pass.html"})
    public String editPass(){
        return "edit_pass";
    }

    @PostMapping("/modifyPassword")
    public String modifyPassword(String newPass, String oldPass,String newPassCon,
                              @SessionAttribute("loginUser") LoginUser loginUser,
                              Model model){
        model.addAttribute("loginUser",loginUser);
        Map map = loginUserService.modifyPassword(loginUser,oldPass,newPass,newPassCon);
        model.addAllAttributes(map);
        return "edit_pass";
    }
}
